import os
import json
import gradio as gr
from openai import OpenAI

def load_config():
    try:
        with open('config.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

# 获取API密钥
config = load_config()
api_key = os.getenv('DEEPSEEK_API_KEY') or config.get('DEEPSEEK_API_KEY')

if not api_key:
    # 创建示例配置文件
    example_config = {
        "DEEPSEEK_API_KEY": "sk-90084af94f7e41859be43bd5e84a24fd"
    }
    with open('config.json', 'w', encoding='utf-8') as f:
        json.dump(example_config, f, indent=4)
    
    raise ValueError("""
请设置DeepSeek API密钥，您可以通过以下方式之一进行设置：

1. 在config.json文件中设置DEEPSEEK_API_KEY（推荐）
2. 设置系统环境变量DEEPSEEK_API_KEY
3. 在运行程序前设置临时环境变量：
   - Windows CMD: set DEEPSEEK_API_KEY=your-api-key
   - Windows PowerShell: $env:DEEPSEEK_API_KEY='your-api-key'
   - Linux/Mac: export DEEPSEEK_API_KEY=your-api-key
    """)

# 初始化OpenAI客户端
client = OpenAI(
    api_key=api_key,
    base_url="https://api.deepseek.com/v1/"
)

def chat_with_ai(message, history):
    # 将历史对话格式化为OpenAI API所需的格式
    messages = []
    for human, assistant in history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": assistant})
    messages.append({"role": "user", "content": message})
    
    try:
        # 调用DeepSeek API
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            temperature=0.7,
            max_tokens=1000,
            stream=False
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"发生错误: {str(e)}"

# 创建Gradio界面
with gr.Blocks() as demo:
    gr.Markdown("## 奉孝AI助手", elem_classes=["centered-title"], css=".centered-title {text-align: center; margin: 20px auto; display: block; width: 100%;}");
    
    chatbot = gr.Chatbot(
        [],
        height=500,
        show_label=False,
        container=True,
        avatar_images=(None, None),
        elem_classes="chatbot-container"
    )
    msg = gr.Textbox(
        placeholder="在这里输入您的问题...",
        show_label=False,
        container=True,
        scale=7,
        min_width=400,
        elem_classes="input-textbox"
    )
    
    # 添加自定义CSS样式
    gr.Markdown("""
    <style>
    .input-textbox {
        z-index: 1000 !important;
        position: relative !important;
    }
    .chatbot-container {
        margin-bottom: 20px;
    }
    </style>
    """)
    clear = gr.Button("清空对话")

    def user(message, history):
        return "", history + [[message, None]]

    def bot(history):
        if history[-1][1] is None:
            history[-1][1] = chat_with_ai(history[-1][0], history[:-1])
        return history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )

    clear.click(lambda: None, None, chatbot, queue=False)

# 启动应用
if __name__ == "__main__":
    demo.launch(share=False, server_port=7861)